<?php

/**
 * Description of Generic
 *
 * @author Kam
 */
class Application_Form_Offer_Generic extends My_Form_Frontened {

    protected $categoryId;
    protected $bean;

    /** @var Zend_From_Element[] */
    protected $attributes;
    protected $template;

    public function __construct($categoryId, $bean, $options = null) {
        $this->categoryId = $categoryId;
        $this->bean = $bean;
        parent::__construct($options);
    }

    public function init() {
        $this->addStylesheet('/css/form/offer.css');
        $this->_mainCss = 'offer-add-form';
        $this->setTitle($this->translate('XXX_OFFER_ADD_FORM_TITLE'));

        $title = new Zend_Form_Element_Text('title');
        $title->setLabel(_('XXX_OFFER_ADD_FORM_TITLE_LABEL'));
        $title->setRequired();
        $title->setAttrib('class', 'element-big');
        $this->addElement($title);

        $props = My_Utils::getOfferProperties();
        $type = $this->bean->type;
        if($props[$type][My_Utils::PROP_OFFER_WYSWIG]) {
            $content = new My_Form_Element_Wyswig('content');
            $content->addFilter(new Zend_Filter_StripTags(array(
                        'allowTags' => array('b', 'br', 'i', 'u', 'ul', 'li', 'ol', 'blockquote'),
                    )));
        } else {
            $content = new Zend_Form_Element_Textarea('content');
            $content->addFilter(new Zend_Filter_StripTags());
            $this->setAutosized($content);
        }
        $content->setLabel(_('XXX_OFFER_ADD_FORM_CONTENT_LABEL'));
        $content->addValidator(new Zend_Validate_StringLength(array('max' => $props[$type][My_Utils::PROP_OFFER_DESC_LIMIT])));
        $content->setRequired();
        $content->setAttrib('class', 'element-big');
        $this->addElement($content);

        $this->initAttributes();

        $contactName = new Zend_Form_Element_Text('contact_name');
        $contactName->setLabel(_('XXX_OFFER_ADD_FORM_CONTACT_NAME_LABEL'));
        $contactName->setRequired();
        $this->addElement($contactName);

        $contactPhone = new Zend_Form_Element_Text('contact_phone');
        $contactPhone->setLabel(_('XXX_OFFER_ADD_FORM_CONTACT_PHONE_LABEL'));
        $this->addElement($contactPhone);

        $contactEmail = new Zend_Form_Element_Text('contact_email');
        $contactEmail->setLabel(_('XXX_OFFER_ADD_FORM_CONTACT_EMAIL_LABEL'));
        $contactEmail->setRequired();
        $contactEmail->addValidator('EmailAddress');
        $this->addElement($contactEmail);

        $contactEmailVisible = new Zend_Form_Element_Checkbox('contact_email_visible_flag');
        $contactEmailVisible->setLabel(_('XXX_OFFER_ADD_FORM_CONTACT_EMAIL_VISIBLE_FLAG_LABEL'));
        $this->addElement($contactEmailVisible);

        $contactSkype = new Zend_Form_Element_Text('contact_skype');
        $contactSkype->setLabel(_('XXX_OFFER_ADD_FORM_CONTACT_SKYPE_LABEL'));
        $this->addElement($contactSkype);

        $contactGG = new Zend_Form_Element_Text('contact_gg');
        $contactGG->setLabel(_('XXX_OFFER_ADD_FORM_CONTACT_GG_LABEL'));
        $this->addElement($contactGG);

        $this->_addFormCancel = true;
        $this->_formCancelOptions['position'] = 'left';
        $this->_formCancelOptions['label'] = $this->translate('XXX_OFFER_ADD_FORM_CANCEL_LABEL');
        $this->_formCancelOptions['url'] = $this->getView()->url(array('action' => 'step-prev'), 'default', false);
        $this->addSubmitElement()->setLabel(_('XXX_OFFER_ADD_FORM_SUBMIT_BTN'));

        $this->addDisplayGroup(array($title, $content), 'basic', array('legend' => _('XXX_OFER_ADD_FORM_SECTION_BASIC')));

//        d(array_values($this->attributes));
        if (!empty($this->attributes)) {
            $this->addDisplayGroup(array_values($this->attributes), 'attr', array('legend' => _('XXX_OFER_ADD_FORM_SECTION_ADDITIONAL')));
        }

        $this->addDisplayGroup(array($contactName, $contactPhone, $contactEmail, $contactEmailVisible, $contactSkype, $contactGG), 'contact', array('legend' => _('XXX_OFFER_ADD_FORM_SECTION_CONTACT')));

        $this->addDisplayGroup(array($this->getSubmitElement()), 'action', array('legend' => ''));

//        $dec = array(
//            'FormElements',
//            array('Fieldset', array('class' => 'span12')),
////            array('HtmlTag', array('tag' => 'div', '____closeOnly' => true))
//        );
//        $this->getDisplayGroup('basic')->setDecorators($dec);
//        if (!empty($this->attributes)) {
//            $this->getDisplayGroup('attr')->setDecorators($dec);
//        }
//        $this->getDisplayGroup('action')->setDecorators($dec);
//        $this->getDisplayGroup('contact')->setDecorators($dec);

        $user = My_Utils::getCurrentUser();
        if (!empty($user)) {
            $elements = $this->getDisplayGroup('contact')->getElements();
            /* @var $el Zend_Form_Element_Xhtml */
            foreach ($elements as $el) {
                $key = $el->getName();
                if (isset($user[$key])) {
                    $el->setValue($user[$key]);
                }
            }
        }
    }

    public function initAttributes() {
        $this->attributes = array();
        $templateId = $this->bean->offerTemplateId;
        $daoOfferTemplate = new Application_Model_DAO_OfferTemplate();
        $template = $this->template = $daoOfferTemplate->getTemplate($templateId);
        if (empty($template)) {
            return;
        }
        $attrs = $template['attributes'];
        foreach ($attrs as $att) {
            $elem = $this->createGenericElement($att);
            $this->attributes[$elem->getName()] = $elem;
            $this->addElement($elem);
        }
    }

    protected function createGenericElement($att) {
        $elementType = $att['input_type'];
        $elementTypeMap = array('number' => 'text');
        if (isset($elementTypeMap[$elementType])) {
            $elementType = $elementTypeMap[$elementType];
        }
        $elem = $this->createElement($elementType, 'otaid_' . $att['offer_template_attribute_id']);
        if ($elem instanceof Zend_Form_Element_Select) {
            $data = $att['input_params'];
            if (!empty($data)) {
                $data = Zend_Json::decode($data);
                $data2 = array('' => '');
                foreach ($data as $v) {
                    $data2[$v] = $v;
                }
                $elem->setMultiOptions($data2);
            }
        }
        if ($elem instanceof Zend_Form_Element_Checkbox) {
            $elem = $this->createElement('select', $elem->getName());
            $data = array('' => '', $this->translate('XXX_YES') => $this->translate('XXX_YES'), $this->translate('XX_NO') => $this->translate('XX_NO'));
            $elem->setMultiOptions($data);
        }
        $elem->setLabel($att['display_pl']);
        if ($att['required']) {
            $elem->setRequired();
        }
        if ($att['size'] == 'big') {
            $elem->setAttrib('class', 'element-big');
        }
        return $elem;
    }

    public function ___loadDefaultDecorators() {
        $groupDecorator = array(
            'FormElements',
            array('Fieldset'), //, array('class' => 'span12')),
        );
        $ds = $this->getDisplayGroups();
        foreach ($ds as $dk => $d) {
            $this->getDisplayGroup($dk)->setDecorators($groupDecorator);
        }
        $this->addStylesheet('/css/form/offer.css');
        $this->_mainCss = 'offer-add-form';
        $elems = $this->getElements();
        /* @var $e Zend_Form_Element */
        foreach ($elems as $e) {
            if ($e instanceof Zend_Form_Element_File) {
                continue;
            }
            $css = $e->getAttrib('class');
            $isBig = false;
            if (stripos($css, 'element-big') !== false) {
                $labelSpan = 'span2';
                $dataSpan = 'span10';
                $isBig = true;
            } else {
                $labelSpan = 'span4';
                $dataSpan = 'span8';
            }
            $spanRow = '';
            $isControlGroupCSS = true;
            $elementType = $this->getElementType($e);
            $class = 'type-' . $elementType . ' element-' . $e->getId();
            if ($e->hasErrors()) {
                $class .= ' error';
            }

            $decorators = array();
            $decorators[] = array('ViewHelper');
            $elementCss = $e->getAttrib('class');
            $e->setAttrib('class', '');

            if ($e instanceof Zend_Form_Element_Button || $e instanceof Zend_Form_Element_Submit) {
                $e->setAttrib('class', 'form_button button ' . $e->getAttrib('class'));
            }
            if ($e instanceof Zend_Form_Element_Submit) {
                $e->setAttrib('class', 'btn btn-primary btn-large submit ' . $e->getAttrib('class'));
                if ($this->_addFormCancel) {
                    $decorators[] = array('FormCancel', $this->_formCancelOptions);
                }
                $isControlGroupCSS = false;
                $spanRow = '';
                $labelSpan = 'span1';
                $dataSpan = 'span12';
                $isBig = true;
            }
            $decorators[] = array('Description', array('tag' => 'div', 'class' => 'description'));
            $decorators[] = 'Errors';
            $decorators[] = array(array('data' => 'HtmlTag'), array('tag' => 'div', 'class' => ($isControlGroupCSS ? 'controls ' : '') . $dataSpan . ' data type-' . $elementType . ' element-' . $e->getId()));
            if ($this->_showLabels) {
                if ($e instanceof Zend_Form_Element_Button || $e instanceof Zend_Form_Element_Submit) {
                    $decorators[] = array('Label', array('tag' => 'div', 'class' => 'label-hidden', 'tagClass' => 'label-column ' . ($isControlGroupCSS ? 'control-label' : '')));
                } else {
                    $decorators[] = array('Label', array('tag' => 'div', 'class' => 'label', 'tagClass' => $labelSpan . ' label-column ' . ($isControlGroupCSS ? 'control-label' : '')));
                }
            }
            $decorators[] = array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => ($isControlGroupCSS ? 'control-group ' : '' ) .($isBig ? 'span12' : 'span6'). ' row-fluid ' . $spanRow . ' row-type-' . $elementType . ' row-' . $e->getId() . ' ' . str_replace(array('btn-primary', 'btn-large', 'btn-normal', 'btn-mini', 'btn-small', 'btn'), '', $elementCss)));
            $e->setDecorators($decorators);
            $css = $e->getAttrib('class');
            if (!($e instanceof Zend_Form_Element_Button || $e instanceof Zend_Form_Element_Submit)) {
            $e->setAttrib('class', $css . ' span12');
            }
        }
        $class = $this->getAttrib('class');
        if (!$class) {
            $class = '';
        }
        $this->setAttrib('class', 'form ' . $this->_mainCss . ' ' . $class);
        $formTitleCss = empty($this->_mainCss) ? '' : $this->_mainCss . '-title';
        $this->setDecorators(array(
            array('FormErrors', array(
                    'ignoreSubForms' => false,
                    'showCustomFormErrors' => true,
                    'onlyCustomFormErrors' => true,
                    'markupElementLabelEnd' => '</b>',
                    'markupElementLabelStart' => '<b>',
                    'markupListItemEnd' => '',
                    'markupListItemStart' => '',
                    'markupListStart' => '<div class="form-errors">',
                    'markupListEnd' => '</div>',
                )
            ),
            'FormElements',
            array('HtmlTag', array('tag' => 'div', 'class' => 'form_elements row-fluid')),
            'form',
            array('FormTitle', array('class' => $formTitleCss)),
        ));
    }

    public function render(Zend_View_Interface $view = null) {
        $elements = $this->getElements();
        /* @var $e Zend_Form_Element */
        foreach ($elements as $e) {
//            $decorator = $e->getDecorator('row');
//            $class = $decorator->getOption('class');
//            if ($e->hasErrors()) {
//                $class .= ' error';
//            } else {
//                $class .= ' info';
//            }
//            $decorator->setOption('class', $class);
        }
        return parent::render($view);
    }

}
